package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import com.ruoyi.common.enums.DelFlag;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.SecurityUtils;
import java.util.Date;

/**
 * mybatis plus 插入、更改时统一处理配置
 *
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandlerConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        // 自动注入逻辑删除字段 值为0 代表存在
        strictInsertFill(metaObject, "delFlag", Integer.class, DelFlag.EXIST.getValue());

        // 自动注入创建时间
        strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());

        // 自动注入创建人
        try {
            strictInsertFill(metaObject, "createBy", String.class, SecurityUtils.getUsername());
        } catch (ServiceException ignored) {
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        // 自动注入更新时间
        strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());

        // 自动注入更新人
        try {
            strictUpdateFill(metaObject, "updateBy", String.class, SecurityUtils.getUsername());
        } catch (ServiceException ignored) {
        }
    }
}
